Graphs

Definitions of a Graph

Informal Definition of a Graph: A graph is a nonempty set of nodes (vertices) and a set of arcs (edges) such that arc connects two nodes.

Formal Definition of a Graph: A graph is an ordered triple (N,A,g) where:

Example

Sketch a graph having nodes \{ 1,2,3,4,5 \}, arcs \{ a_1, a_2, a_3, a_4, a_5, a_6 \}, and function g(a_1) = 1-2, g(a_2) = 1-3, g(a_3)=3-4, g(a_5)=4-5, and g(a_6)=5-5

Directed Graphs

Informal Definition of a Directed Graph: Graph where the arcs of a graph begin at one node and end at another.

Formal Definition of a Directed Graph: A directed graph is an ordered triple (N,A,g) where:

Example

Tangent (???): Counting Edges of Graphs

Suppose a fully-connected undirected graph with n nodes. How many ways can you connect the nodes? C(n,2)

Suppose a non-self-pointing fully-connected directed graph with k nodes. How many ways can you connect the nodes? P(k,2)

Tree Terminology

Informal Definition of Tree: Special type of graph, very useful for representation of data

Formal Definition of Tree: Acyclic, connected graph with one node designated as the root of the tree.

More Tree Terminology

Binary Trees

Binary Tree: Tree where each node has at most two children.

Defining Trees Recursively

We can define trees recursively with a base case node and some rules to define children and parents.

Today’s Plan

Applications of Trees

Trees allow us to efficiently search a collection of records to locate a particular record or determine that a record is not in the collection:

Tree Traversal Algorithms

Traversal: Goal is to visit every node in the tree.

Preorder Traversal: The root of the tree is visited first, and then the subtrees are processed left to right, each in preorder.

Inorder Traversal: Left subtree is processed by an inorder traversal, then the root is visited, and then the remaining subtrees are processed from left to right, each in inorder.

Postorder Traversal: Root is visited last, after all subtrees have been processed from left to right in postorder.